package com.spring.task;

import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

//内存级别消息队列
public class TaskQueue {

	private RingBuffer<TaskEvent> ringBuffer = null;
	private Disruptor<TaskEvent> disruptor = new Disruptor<TaskEvent>(TaskEvent.EVENT_FACTORY, 2048, new NamedThreadFactory());

	// 启动消息队列
	public void start() {
		ringBuffer = disruptor.start();
	}

	// 设置消费者
	public void setHandler(final EventHandler<? super TaskEvent> handler) {
		disruptor.handleEventsWith(handler);
	}

	// 向消息队列发布任务
	public void publish(TaskEvent event) {
		long seq = ringBuffer.next();
		TaskEvent eventPub = ringBuffer.get(seq);
		eventPub.setContext(event.getContext());
		ringBuffer.publish(seq);
	}

	// 关闭消息队列
	public void shutdown() {
		disruptor.shutdown();
	}

}
